package com.ruoyi.app.controller;

import com.ruoyi.app.service.AppRegisterService;
import com.ruoyi.app.service.PasswordService;
import com.ruoyi.business.constant.JtUserConstants;
import com.ruoyi.business.domain.JtAppUser;
import com.ruoyi.business.domain.JtCountryCode;
import com.ruoyi.business.service.IJtAppUserService;
import com.ruoyi.business.service.IJtCountryCodeService;
import com.ruoyi.business.service.IJtSmsLogService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.jwt.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 共用
 * @Author Alan Zhang
 * @Date 2025/3/7 10:52
 */
@Controller()
@RequestMapping("/api/public")
public class ApiController extends BaseApiController{

    @Autowired
    private IJtCountryCodeService jtCountryCodeService;
    @Autowired
    private IJtAppUserService iJtAppUserService;
    @Autowired
    private PasswordService passwordService;
    @Autowired
    private AppRegisterService registerService;
    @Autowired
    private IJtSmsLogService jtSmsLogService;

    /**
     * 国家码信息
     * @param lang 语言
     * @return
     */
    @PostMapping("/country/region/list")
    @ResponseBody
    public AjaxResult countryRegionList(String lang)
    {
        System.out.println(i18n("arabic"));
        if(StringUtils.isEmpty(lang)) {
            return AjaxResult.error("语言不能为空！");
        }
        JtCountryCode param = new JtCountryCode();
        param.setStatus(0);
        List<JtCountryCode> list = jtCountryCodeService.selectJtCountryCodeList(param);
        return AjaxResult.success("success", list);
    }

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @param lang 语言
     * @return
     */
    @PostMapping("/signin")
    @ResponseBody
    public AjaxResult login(String username, String password, String lang)
    {
        if(StringUtils.isEmpty(lang)){
            return AjaxResult.error("语言不能为空！");
        }
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            return AjaxResult.error("账号和密码不能为空!");
        }

        JtAppUser user = iJtAppUserService.selectUserByPhoneNumber(username);
        if (user == null)
        {
            return AjaxResult.error("用户不存在/密码错误!");
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            return AjaxResult.error("用户已封禁，请联系管理员!");
        }

        if (!passwordService.matches(user, password))
        {
            return AjaxResult.error("用户不存在/密码错误!");
        }

        String token = JwtUtils.createToken(username, user.getPassword());
        String ip = IpUtils.getIpAddr(getRequest());
        JtAppUser jtAppUser = new JtAppUser();
        jtAppUser.setUserId(user.getUserId());
        jtAppUser.setLoginDate(DateUtils.getNowDate());
        jtAppUser.setLoginIp(ip);
        iJtAppUserService.updateJtAppUser(jtAppUser);
        return AjaxResult.success("登录成功,请妥善保管您的token信息", token);
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/signup")
    @ResponseBody
    public AjaxResult register(@Validated JtAppUser user, String smsCode)
    {
        if(StringUtils.isEmpty(user.getLang())){
            return AjaxResult.error("语言不能为空！");
        }
        if(StringUtils.isEmpty(smsCode)){
           return AjaxResult.error("请填写验证码！");
        }
        if(smsCode.length() > 7){
            return AjaxResult.error("验证码格式错误！");
        }
        boolean validRes = jtSmsLogService.validSmsCode(user.getCountryCode(), user.getPhoneNumber(), smsCode, JtUserConstants.SMS_SIGN_UP_STATUS);
        if(!validRes){
            return AjaxResult.error("短信验证码无效！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? AjaxResult.success() : AjaxResult.error(msg);
    }



    /**
     * 注册 发送短信
     * @return
     */
    @PostMapping("/send/sms")
    @ResponseBody
    public AjaxResult sendSms(Integer countryCode, String phoneNumber, String lang) throws Exception {
        return sendSmsCode(countryCode, phoneNumber, lang, JtUserConstants.SMS_SIGN_UP_STATUS);
    }


    /**
     * 发送短信
     * @return
     */
    @PostMapping("/forgot/send/sms")
    @ResponseBody
    public AjaxResult forgotPwdSendSms(Integer countryCode, String phoneNumber, String lang) throws Exception {
        return sendSmsCode(countryCode, phoneNumber, lang, JtUserConstants.SMS_FORGOT_PWD_STATUS);
    }

    public AjaxResult sendSmsCode(Integer countryCode, String phoneNumber, String lang, Integer type) throws Exception {
        if(StringUtils.isEmpty(lang)){
            return AjaxResult.error("语言不能为空！");
        }
        if(countryCode == null){
            return AjaxResult.error("国家码必填");
        }
        if(StringUtils.isEmpty(phoneNumber)){
            return AjaxResult.error("手机号码必填");
        }
        if(86 == countryCode){
            if (phoneNumber.length() != 11 || !org.apache.commons.lang3.StringUtils.isNumeric(phoneNumber)) {
                return AjaxResult.error("手机格式错误");
            }
        } else {
            if (phoneNumber.length() > 12 || !org.apache.commons.lang3.StringUtils.isNumeric(phoneNumber)) {
                return AjaxResult.error("手机格式错误");
            }
        }
        return jtSmsLogService.sendSms(countryCode, phoneNumber, type);
    }


    @PostMapping("/reset/pwd")
    @ResponseBody
    public AjaxResult resetPwd(Integer countryCode, String phoneNumber, String lang, String smsCode, String newPassword)
    {
        if(countryCode == null || StringUtils.isEmpty(phoneNumber)){
            return AjaxResult.error("国家码或手机号不能为空！");
        }
        if(StringUtils.isEmpty(smsCode) || smsCode.length() > 7){
            return AjaxResult.error("短信验证码不正确！");
        }
        boolean validRes = jtSmsLogService.validSmsCode(countryCode, phoneNumber, smsCode, JtUserConstants.SMS_FORGOT_PWD_STATUS);
        if(!validRes){
            return AjaxResult.error("短信验证码无效！");
        }
        JtAppUser jtAppUser = jtAppUserService.selectUserByPhoneNumber(phoneNumber);

        JtAppUser user = new JtAppUser();
        user.setUserId(jtAppUser.getUserId());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(jtAppUser.getPhoneNumber(), newPassword, user.getSalt()));
        user.setPwdUpdateDate(DateUtils.getNowDate());
        if (jtAppUserService.resetUserPwd(user) > 0)
        {
            //setSysUser(jtAppUserService.selectJtAppUserList(user.getUserId()));
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }
}
